package com.ys.controller.api.finance;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bo.util.DateUtil;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwAccountDetailedForCompany;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.business.YsbExportLogService.ExportDto;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwAccountDetailedForCompany")
public class ApiInterTcwAccountDetailedForCompanyController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TcwAccountDetailedForCompany> commonApiService;
	@Autowired
	private YsbExportLogService ysbExportLogService;

	@RequiresPermissions("tcwAccountDetailedForCompany:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TcwAccountDetailedForCompany cond,
			String conditions
			){
		
		String _ys_year = ConditionUtil.getConditionValue(conditions, "_ys_year");
		System.out.println("_ys_year-----" + _ys_year);
		
		if (_ys_year != null && _ys_year.length() == 4) {
			
			String yyyy = DateUtil.getYYYY(new Date());
			if (_ys_year.equals(yyyy)) {
				cond.setMainTable("TCW_AccountDetailedForCompany");
			} else {
				cond.setMainTable("kjecp_history.dbo.TCW_AccountDetailedForCompany_" + _ys_year);
			}
			
			String _ys_inout = ConditionUtil.getConditionValue(conditions, "_ys_inout");
			if (_ys_inout != null && _ys_inout.length() > 0) {
				if ("1".equals(_ys_inout)) {
					cond.where("A.Fje >= 0");
				} else {
					cond.where("A.Fje < 0");
				}
			}
		} else {
			cond.where("1=0");
		}

		cond.addField("ISNULL(A.Fje-A.FjeLeft,0)AS fjeLeftBefore");
		cond.setOrderby("A.Djysj desc");
		cond = commonApiService.dataAuth(MenuId.TCW_AccountDetailedForCompany_By_New, cond);
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		{
			JSONObject JO = new JSONObject();
			
			// 订单数累计
			JO.put("fJe", "合计:" + cond.setFields("ISNULL(SUM(A.Fje),0)").sumDecimal().setScale(2, BigDecimal.ROUND_HALF_UP));


			vo.setTotalRow(JO);
		}
		return vo;
	}

	/*
	 * 供费用返还单调取使用
	 */
	@RequestMapping("/searchForRunningBack")
    @ResponseBody
	public LayuiTableVoJA searchForRunningBack(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TcwAccountDetailedForCompany cond
			){
		
		cond.setOrderby("A.Id desc");
		
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		return vo;
	}

	@RequiresPermissions("tcwAccountDetailedForCompany:view")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAccountDetailedForCompany cond, String conditions) throws Exception{
		
		cond.setPage(0).setSize(999999);
		
		String _ys_year = ConditionUtil.getConditionValue(conditions, "_ys_year");
		System.out.println("_ys_year-----" + _ys_year);
		
		if (_ys_year != null && _ys_year.length() == 4) {
			
			if (_ys_year.equals("2023")) {
				cond.setMainTable("TCW_AccountDetailedForCompany");
			} else {
				cond.setMainTable("TCW_AccountDetailedForCompany_" + _ys_year);
			}
			
			String _ys_inout = ConditionUtil.getConditionValue(conditions, "_ys_inout");
			if (_ys_inout != null && _ys_inout.length() > 0) {
				if ("1".equals(_ys_inout)) {
					cond.where("A.Fje >= 0");
				} else {
					cond.where("A.Fje < 0");
				}
			}

			String dshsj = ConditionUtil.getConditionValue(conditions, "dshsj");
			if (dshsj != null && dshsj.length() > 0) {
				
				String[] dshsjs = dshsj.split(" ~ ");
				String dshsjBegin = dshsjs[0];
				String dshsjEnd = dshsjs[1];
				
				String max = DateUtil.getYYYY_MM_DD(DateUtil.addDays(DateUtil.parseYYYY_MM_dd(dshsjBegin.substring(0, 10)), 35));
				if (dshsjEnd.compareTo(max) < 0) {
					
					ExportDto dto1 = ysbExportLogService.init(MenuId.TCW_AccountDetailedForCompany);
					if (dto1.getCode() == ExportDto.Code.FAILED.value) {
						return R.error(dto1.getMsg());
					} else {
						try {
							cond.setOrderby("A.Djysj desc");
							List<Map<String, Object>> listData = cond.queryMap();
					        
					    	List<YsCol> listField = new YsCol()
					    			.setMenuId(MenuId.TCW_AccountDetailedForCompany)
					    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
					    			.setOrderby("A.SortNo asc")
					    			.queryList();
					    	
					        ExportExcelUtils<TcwAccountDetailedForCompany> util = new ExportExcelUtils<TcwAccountDetailedForCompany>(new TcwAccountDetailedForCompany());
					        
					        String toFilePath = util.exportExcel(listData, listField, "历年公司账户流水");
					        UploadDto dto2 = commonApiService.uploadLocalToServer(toFilePath);
					        ysbExportLogService.updateSuccess(dto1.getId(), dto2.getUrl());
					        
					        return R.ok("已经生成完毕");
						} catch (Exception e) {
					        ysbExportLogService.updateFail(dto1.getId());
					        
					        return R.error("生成失败，请联系客服");
						}
					}
				} else {
			        return R.error("时间范围不能超过35天");
				}
			} else {
		        return R.error("必须指定时间范围");
			}
			
		} else {
	        return R.error("必须指定年份");
		}
    }


	/**
	 * 弹出框
	 */
	@RequestMapping("/modalByExpenseSettleReturn")
	@ResponseBody
	public LayuiTableVoJA searchForModalByExpenseSettleReturn(@ModelAttribute TcwAccountDetailedForCompany cond){

		cond.addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm")//运营公司
				.addLeftJoin("THR_OperateCompanyApply PC ON PC.Vgsbm = A.Vgsbmp")//对方公司

				.where("A.Fje > 0")//只调取金额大于0的流水
				//运营账户 需要互相对应 非运营账户   运营属性(1公司账户、2运营账户、3过渡账户、4直营账户)
				.where("(C.OperationsAttribute = 2 AND PC.OperationsAttribute IN (1,3,4)) OR (C.OperationsAttribute IN (1,3,4) AND PC.OperationsAttribute = 2 ) ")
				//调取未被调取过的
				.where("( SELECT COUNT ( 1 ) AS num FROM TCW_ExpenseSettleReturnItem B WHERE B.AccountDetailedForCompanyId = A.Id ) = 0 ")

				//倒序
				.setOrderby("A.Djysj DESC");

		return commonApiService.searchLay(cond);
	}
}
